package controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import beans.UserBean;

import java.sql.*;
import model.UserDAO;


@WebServlet("/SignupServlet")
public class SignupServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public SignupServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try
		{	    

			UserBean user = new UserBean();
			user.setEmail(request.getParameter("email"));
			user.setPassword(request.getParameter("password"));
			user.setName(request.getParameter("name") + " " + request.getParameter("surname"));
			boolean genderbool;
			String gender = request.getParameter("gender");
			if (gender.equals("TRUE"))
				genderbool = true;
			else
				genderbool = false;
			user.setGenderMale(genderbool);
			String birthdate = request.getParameter("year") + "-" + request.getParameter("month") + "-" + request.getParameter("day");
			user.setBirthDate(Date.valueOf(birthdate));
			user.setCity(request.getParameter("city"));
			user.setRegion(request.getParameter("region"));
			user.setCountry(request.getParameter("country"));

			user = UserDAO.signup(user);

			if (user.isValid())
			{	        
				HttpSession session = request.getSession(true);
				session.setAttribute("failedLogin", false);
				session.setAttribute("currentSessionUser",user); 
				response.sendRedirect("LoginServlet?un=" + user.getEmail() + "&pw=" + user.getPassword()); //logged-in page      		
			}

			else {
				HttpSession session = request.getSession(true);
				session.setAttribute("failedLogin", true);
				response.sendRedirect("login.jsp"); //loopback to login page to display error message
			}
		} 


		catch (Throwable theException) 	    
		{
			System.out.println(theException); 
		}	}

}